﻿using Meiam.System.Interfaces;
using Microsoft.Extensions.Logging;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Meiam.System.Tasks
{
    public class JobCheckDeviceInfo : JobBase, IJob
    {
        private readonly ISysTasksQzService _tasksQzService;
        private readonly ICheckDeviceInfoService _checkDeviceInfoService;
        private readonly ILogger<JobCheckDeviceInfo> _logger;
        public JobCheckDeviceInfo(ILogger<JobCheckDeviceInfo> logger, ISysTasksQzService tasksQzService, ICheckDeviceInfoService checkDeviceInfoService)
        {
            _logger = logger;
            _tasksQzService = tasksQzService;
            _checkDeviceInfoService = checkDeviceInfoService;
        }
        /// <summary>
        /// 日志管理接口
        /// </summary>

        public async Task Execute(IJobExecutionContext context)
        {
            var executeLog = await ExecuteJob(context, async () => await Run(context));
            // var executeLog = await ExecuteJob(context, async () => await Run(context));


            // 可以直接获取 JobDetail 的值
            var jobKey = context.JobDetail.Key;
            var jobId = jobKey.Name;
            //var param = context.MergedJobDataMap;

            // 也可以通过数据库配置，获取传递过来的参数
            JobDataMap data = context.JobDetail.JobDataMap;
            //int jobId = data.GetInt("JobParam");

            var model = _tasksQzService.GetId(jobId);

            if (model != null)
            {
                model.RunTimes += 1;
                model.Remark = logWrite(executeLog);


                _tasksQzService.Update(model);
            }

            _logger.LogInformation(executeLog);
        }

        public async Task Run(IJobExecutionContext context)
        {

            var jobKey = context.JobDetail.Key;
            var jobId = jobKey.Name;

            var model = _tasksQzService.GetId(jobId);

            if (model != null)
            {
                await _checkDeviceInfoService.Run(model.JobParams);
            }

            await Task.Delay(1);
        }
    }
}
